package system

import (
	"context"
	"time"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddPostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
	postModel model.SysPostModel
}

func NewAddPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddPostLogic {
	return &AddPostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		postModel: model.NewSysPostModel(svcCtx.Orm),
	}
}

func (l *AddPostLogic) AddPost(req *types.AddPostRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel, l.ctx, "system:post:add")
	if err != nil {
		return nil, errorx.Unauthorized
	}
	authinfo,err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil,errorx.AuthNoFound
	}
	post := &model.SysPost{}
	if len(req.PostCode) <= 0 {
		return nil,errorx.NewBizError(500,"岗位编码不能为空")
	}
	post.PostCode = req.PostCode
	if len(req.PostName) <= 0 {
		return nil,errorx.NewBizError(500,"岗位名称不能为空")
	}
	post.PostName = req.PostName
	if req.PostSort <= 0 {
		return nil,errorx.NewBizError(500,"岗位排序不能为空")
	}
	post.PostSort = req.PostSort
	post.Status = common.NORMAL_STATUS
	if len(req.Status) > 0 {
		post.Status = req.Status
	}
	post.CreateBy = authinfo.NickName
	post.CreateTime = time.Now().Unix()
	post.UpdateBy = authinfo.NickName
	post.UpdateTime = time.Now().Unix()
	postId,err := l.postModel.InsertGetId(l.ctx,nil,post)
	if err != nil {
		return nil,errorx.SqlInsertError
	}

	return &types.CommonResponse{
		Status: 200,
		Msg: "更新成功",
		Data: types.IdResponse{
			Id: postId,
		},
	},err
}
